package com.ltmonitor.web.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.Department;
import com.ltmonitor.vo.PaginateResult;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;

import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

/**
 * 数据处理控制器，主要用于对数据进行处理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/dataProcess")
public class DataProcessController extends PaginateAction {
	private Logger mylog = Logger.getLogger("debug");
	
	
	/**
	 * 请求不连续轨迹页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/viewDiscontinuityLinePage.action")
	public String viewDiscontinuityLinePage(Model model) {
//		model.addAttribute("message", "discontinuityPage");
		return "dataProcess/discontinuityLinePage";
	}
	
	/**
	 * 请求不连续轨迹超速位移页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/viewDiscontinuityFastListPage.action")
	public String viewDiscontinuityFastListPage(Model model) {
		return "dataProcess/discontinuityFastListPage";
	}
	
	
	/**
	 * 请求加入车辆信息
	 * @param model
	 * @return
	 */
	@RequestMapping("/viewImportVehPage.action")
	public String viewImportVehPage(Model model) {
		model.addAttribute("message", "importVehPage");
		return "dataProcess/importVehPage";
	}
	
	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////数据请求
	
	
	
	
	
	/**
	 * 请求获取不连续轨迹数据
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping("/getDiscontinuityData.action ")
	@ResponseBody
	public JsonMessage getDiscontinuityData(@RequestBody String jsonStr) {
		JsonMessage result = null;
		String msg = "";
		try {
			
			// 用于获取用户权限信息
			OnlineUser user = super.getOnlineUser();
			if(user != null) {
				
				Map map = JSONObject.fromObject(jsonStr);
				
				//获取查询部门编号
				getBasicQueryData(user, map);
				
				
				if(map.get("queryId") != null) {
					String queryId = map.get("queryId").toString();
					int pageNum = 1;//默认分页设置
					int pageSize = 0;
					if(map.containsKey("pageNumber")) {
						pageNum = Integer.valueOf(map.get("pageNumber").toString());
					}
					if(map.containsKey("pageSize")) {
						pageSize = Integer.valueOf(map.get("pageSize").toString());
					}
					if(pageSize > 0) {
						PaginateResult list =  queryService.queryByPagination(queryId, map, pageNum, pageSize);
						result = new JsonMessage(true, list);						
					}else {
						msg += "分页数量参数获取失败！";
					}
					
					
				}else {
					msg += "getDirectinuityData-->获取查询语句失败！";
				}				
			}
			
			if(!msg.equals("")) {
				result = new JsonMessage(false, msg);
			}else {
				if( result == null) {
					result = new JsonMessage(false, "获取数据失败！");
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			msg += "getDirectinuityData-->获取不连续轨迹数据失败：" + e.getMessage();
			mylog.error(msg);
			result = new JsonMessage(false, msg);
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * <p>根据用户基本信息获取部门查询条件</p>
	 * <p>首先根据部门编号depId获取部门链表</p>
	 * <p>如果部门编号depId为空，则通过userId查询用户权限下所有部门</p>
	 * <p>把获取的数据放入map中，key为"depIdList"</p>
	 * @param user 当前用户
	 * @param map 查询条件集合
	 */
	private void getBasicQueryData(OnlineUser user, Map map) {
		if (user != null) {
			// 获取用户id
			long userId = user.getEntityId();
			map.put("userId", userId);
			// 根据用户id获取部门列表
			Integer depId = 0;
			if(map.get("depId") != null) {
				depId = Integer.valueOf(map.get("depId").toString());
			}

			if (depId > 0) {
				List<Long> depIdList = super.getDepartmentService().getDepIdList(depId);
				map.put("depIdList", depIdList);
				map.remove("depId");
			} else {
				// 如果部门编号为空，查询所有，那么通过userId获取部门编号
				if (userId > 0) {
					List<Department> list = super.getDepartmentService().getDepartmentListByUserId(userId);
					if (list.size() > 0) {
						List<Long> depIdList2 = new ArrayList<Long>();
						for (Department temp : list) {
							depIdList2.add(temp.getEntityId());
						}
						map.put("depIdList", depIdList2);
						map.remove("depId");
					}
				}
			} // end depId
		} // end user
	}	
	
	
	
	
	/**
	 * 请求插入一条车辆数据
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping("/insertOneVehData.action")
	@ResponseBody
 	public JsonMessage insertOneTermVehData(@RequestBody String jsonStr) {
		JsonMessage result = null;
		String msg = "";
		try {
//			System.out.println("插入一条数据！");
			Map map = JSONObject.fromObject(jsonStr);
			int flg = -1;//定义数据标记，0表示该数据已经存在，无需添加，1表示数据都不能存在，可以添加
			msg += checkOneVehData(map);
			if(msg.equals("")) {
				if(map.get("termExist") != null && map.get("vehExist") != null) {
					//都存在，无需插入
					flg = 0;
				}else {
					//都不存在，可以插入
					flg = 1;
					
					//插入终端数据
					Map termMap = getOneTermData(map);
					msg += insertOneTermData(termMap);
					if(termMap.get("termId") == null) {
						msg += "插入终端数据失败,无法获取终端数据Id !";
					}
					
					//判断信息并插入车辆数据
					if(msg.equals("")) {
						Map vehMap = getOneVehData(map);
						vehMap.put("termId", termMap.get("termId"));
						msg += insertOneVehData(vehMap);
					}
				}
			}
			
			
			//返回结果
			if(msg.equals("")) {
				result = new JsonMessage(true, flg);	
				mylog.info("插入一个车辆数据成功，车辆数据：" + map.toString());
			}else {
				result = new JsonMessage(false, msg);
				mylog.error("插入一个车辆数据失败 ， 原因：" + msg );
				mylog.error("车辆数据：" + map.toString());
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			msg += "插入车辆数据失败：" + e.getMessage();
			result = new JsonMessage(false, msg);
			e.printStackTrace();
		}
		
		return result;
	}
	
	// 校验数据是否存在
	private String checkOneVehData(Map map) {
		String msg = "";
		try {
			// 获取车组
			String queryId = "dataProcess.selectDepIdByName";
			List depList = queryService.query(queryId, map);
			if (depList != null && depList.size() > 0) {
				Map temp = (Map) depList.get(0);
				map.put("depId", temp.get("depId"));
			} else {
				msg += "获取车组失败！";
			}

			// 获取终端
			String termId = "0";// 定以终端数据
			queryId = "dataProcess.selectTermData";
			List termList = queryService.query(queryId, map);
			if (termList != null) {
				if (termList.size() > 0) {
					Map temp = (Map) termList.get(0);
					termId = temp.get("termId").toString();
					// 存在车组
					if (map.get("simNo").toString().equals(temp.get("simNo").toString())
							&& map.get("termNo").toString().equals(temp.get("termNo").toString())) {
						map.put("termExist", 1);
					} else {
						msg += "当前要插入的车组数据已存在！";
						msg += "数据库中 termId = " + temp.get("termId").toString();
					}
				}
			} else {
				msg += "查询终端数据发生错误!";
			}

			// 获取车辆
			queryId = "dataProcess.selectVehData";
			List vehList = queryService.query(queryId, map);
			if (vehList != null) {
				if (vehList.size() > 0) {
					Map vehTemp = (Map) vehList.get(0);
					if (map.get("plateNo").toString().equals(vehTemp.get("plateNo").toString())
							&& map.get("simNo").toString().equals(vehTemp.get("simNo").toString())
							&& vehTemp.get("termId").toString().equals(termId)) {
						map.put("vehExist", 1);
					} else {
						msg += "当前要插入的车辆数据已存在！";
						msg += "数据库中 vehId = " + vehTemp.get("vehicleId").toString();
					}
				}
			} else {
				msg += "查询车辆数据发生错误！";
			}

		} catch (Exception e) {
			// TODO: handle exception
			msg += "校验车辆数据失败：" + e.getMessage();
			e.printStackTrace();
		}
		return msg;
	}

	// 从一个集合数据中，获取终端数据
	private Map getOneTermData(Map map) {
		Map termMap = new HashMap();
		String msg = "";
		termMap.put("simNo", map.get("simNo"));
		termMap.put("seqNo", map.get("seqNo"));
		termMap.put("termNo", map.get("termNo"));
		termMap.put("termType", map.get("termType"));
		termMap.put("depId", map.get("depId"));
		termMap.put("installTime", map.get("installDate"));
		
		// 补全数据
		termMap.put("createDate", new Date());
		termMap.put("deleted", 0);
		termMap.put("bind", 1);
		termMap.put("makeTime", new Date());
		termMap.put("state", 0);
		termMap.put("companyId","117440546");

		return termMap;
	}

	// 插入一个终端数据
	private String insertOneTermData(Map map) {
		String msg = "";
		try {
			String queryId = "dataProcess.insertOneTermData";
			queryService.insert(queryId, map);
			if (map.get("termId") != null) {
				
			} else {
				msg += "获取终端id失败！插入终端数据失败！";
			}

		} catch (Exception e) {
			// TODO: handle exception
			msg += "插入终端数据失败：" + e.getMessage();
			e.printStackTrace();
		}

		return msg;
	}

	// 从一个集合数据中，获取车辆数据
	private Map getOneVehData(Map map) {
		Map vehMap = new HashMap();
		String msg = "";
		vehMap.put("createDate", map.get("createDate"));
		vehMap.put("depId", map.get("depId"));
		vehMap.put("simNo", map.get("simNo"));
		vehMap.put("seqNo", map.get("seqNo"));
		vehMap.put("plateColor", map.get("plateColor"));
		vehMap.put("plateNo", map.get("plateNo"));
		vehMap.put("useType", map.get("useType"));
		vehMap.put("installDate", map.get("installDate"));
		if(map.get("endDate") != null) {
			vehMap.put("endDate", map.get("endDate"));
		}
		
		vehMap.put("deleted", 0);
		vehMap.put("industry", 10);
		vehMap.put("memberId", 0);
		vehMap.put("runStatus", "Normal");
		vehMap.put("workHour", 0);
		vehMap.put("videoChannelNum", 10);
		vehMap.put("companyId", "117440546");

		return vehMap;
	}

	// 插入一个车辆数据
	private String insertOneVehData(Map map) {
		String msg = "";
		try {
			String queryId = "dataProcess.insertOneVehData";
			queryService.insert(queryId, map);
			if (map.get("vehicleId") == null) {
				msg += "获取车辆id失败！插入车辆数据失败！";
			} 
		} catch (Exception e) {
			// TODO: handle exception
			msg += "插入车辆数据失败：" + e.getMessage();
			e.printStackTrace();
		}
		return msg;
	}

}
